package member;


import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ibatis.sqlmap.client.SqlMapClient;

import comm.util.CommUtil;
import comm.util.RequestManager;
import comm.util.SoptHashMap;
import comm.util.SqlMapLoader;

import statics.SoptVars;
public class MemberProc {
	public MemberProc() {
		// TODO Auto-generated constructor stub
	}
	private SqlMapClient sqlMapper = SqlMapLoader.getInstance();
	
	public SoptHashMap regMember(HttpServletRequest request) throws UnsupportedEncodingException{		
		SoptHashMap resultHm = new SoptHashMap();
		SoptHashMap hm = RequestManager.getRequest(request);
		
		if(hm.get("REG_EMAIL")==null || 
				hm.get("REG_PASSWORD")==null || 
				hm.get("REG_PASSWORD_CONFIRM")==null || 
				hm.get("REG_NICK")==null){
			resultHm.put("RESULT", SoptVars.FAIL);
			resultHm.put("ERROR_MSG", "등록에 필요한 정보가 서버에 전달 되지 않았습니다.");
			return resultHm;
		}
		boolean emailChk  = isValidEmail(hm.get("REG_EMAIL").toString());
		boolean nickChk  = isValidNick(hm.get("REG_NICK").toString());
		boolean passChk  = isValidPassword(hm.get("REG_PASSWORD").toString());
		
		if( emailChk && passChk && nickChk){
			try {
				String encryptPw = CommUtil.getMD5(hm.get("REG_PASSWORD").toString());
				hm.remove("REG_PASSWORD");
				hm.remove("REG_PASSWORD_CONFIRM");
				hm.put("REG_PASSWORD", encryptPw);
				if(sqlMapper.insert("member.regMember", hm).toString().length()>0){
					resultHm.put("RESULT", SoptVars.SUCCESS);
					resultHm.put("ERROR_MSG", "회원가입 성공! 로그인 해 주세요:)");
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				resultHm.put("RESULT", SoptVars.FAIL);
				resultHm.put("ERROR_MSG", "데이터베이스에 기록하지 못했습니다.");
			}
		}else{
			resultHm.put("RESULT", SoptVars.FAIL);
			String errorMsg = "";
			if(!emailChk) errorMsg = "이미 사용중인 이메일이거나 사용할 수 없는 이메일입니다.<br>";
			if(!passChk) errorMsg += "사용이 불가능한 패스워드입니다. (4자이상)<br>";
			if(!nickChk) errorMsg += "이미 사용중인 닉네임이거나 사용할 수 없는 닉네임입니다.<br>";
			resultHm.put("ERROR_MSG",errorMsg);
		}
		
		return resultHm;
	}
	
	public SoptHashMap updateMember(HttpServletRequest request) throws UnsupportedEncodingException{		
		SoptHashMap resultHm = new SoptHashMap();
		
		SoptHashMap hm = RequestManager.getRequest(request);
		
		if( hm.get("NICK")==null){
			resultHm.put("RESULT", SoptVars.FAIL);
			resultHm.put("ERROR_MSG", "등록에 필요한 정보가 서버에 전달 되지 않았습니다.");
			return resultHm;
		}
		boolean nickChk = false;
		if(hm.get("NICK").toString().equals(request.getSession().getAttribute("SESSION_MEMBER_NICK").toString())){
			nickChk = true;
		}else{
			nickChk = isValidNick(hm.get("NICK").toString());
		}
		
		if(nickChk){
			try {
				String opens = "";
				opens+=(hm.get("BLOG_OPEN").toString()+" ");
				opens+=(hm.get("MOBILE_OPEN").toString()+" ");
				opens+=(hm.get("TWITTER_OPEN").toString()+" ");
				opens+=(hm.get("ME2DAY_OPEN").toString()+" ");
				opens+=(hm.get("INTRODUCE_OPEN").toString());
				
				hm.put("MEMBER_SEQ", request.getSession().getAttribute("SESSION_MEMBER_SEQ"));
				hm.put("MEMBER_NICK", hm.get("NICK"));
				hm.put("MEMBER_PHONE", hm.get("MOBILE"));
				hm.put("MEMBER_INTRO", hm.get("INTRODUCE"));
				hm.put("MEMBER_HOMEPAGE",hm.get("BLOG"));
				hm.put("MEMBER_OPEN", opens);
				sqlMapper.update("member.updateMember",hm);
				request.getSession().setAttribute("SESSION_MEMBER_NICK", hm.get("NICK"));
				resultHm.put("RESULT", SoptVars.SUCCESS);
				resultHm.put("ERROR_MSG", "저장되었습니다.");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				resultHm.put("RESULT", SoptVars.FAIL);
				resultHm.put("ERROR_MSG", "데이터베이스에 기록하지 못했습니다.");
			}
		}else{
			resultHm.put("RESULT", SoptVars.FAIL);
			String errorMsg = "";
			if(!nickChk) errorMsg += "이미 사용중인 닉네임이거나 사용할 수 없는 닉네임입니다.<br>";
			resultHm.put("ERROR_MSG",errorMsg);
		}
		
		return resultHm;
	}
	
	public SoptHashMap updateMemberImage(HttpServletRequest request,String memberSeq,String imgUrl) throws UnsupportedEncodingException{		
		SoptHashMap resultHm = new SoptHashMap();
		
		if( imgUrl.length()<1){
			resultHm.put("RESULT", SoptVars.FAIL);
			resultHm.put("ERROR_MSG", "등록에 필요한 정보가 서버에 전달 되지 않았습니다.");
			return resultHm;
		}

		try {
			SoptHashMap hm = new SoptHashMap();
			hm.put("MEMBER_SEQ", memberSeq);
			hm.put("MEMBER_PIC_URL", imgUrl);
			Object curImageFileName = sqlMapper.queryForObject("member.getMemberImage",memberSeq);
			if(curImageFileName!=null){
				File curfile = new File(request.getRealPath("wagle/data")+"/"+curImageFileName.toString());
			}
			sqlMapper.update("member.updateMemberImage",hm);
			resultHm.put("RESULT", SoptVars.SUCCESS);
			resultHm.put("ERROR_MSG", "저장되었습니다.");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resultHm.put("RESULT", SoptVars.FAIL);
			resultHm.put("ERROR_MSG", "데이터베이스에 기록하지 못했습니다.");
		}
		return resultHm;
	}
	
	private boolean isValidEmail(String email){
		boolean result = false;
		
		if(email.length()>0)
			try {
				if(sqlMapper.queryForObject("member.isExistEmail",email)==null)
					result = true;
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return result;
			}
		
		return result;
	}
	
	private boolean isValidNick(String nick){
		boolean result = false;
		if(nick.length()>0)
			try {
				if(sqlMapper.queryForObject("member.isExistNick",nick)==null)
					result = true;
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return result;
			}
		
		return result;
	}
	
	private boolean isValidPassword(String pw){
		boolean result = false;
		
		if(pw.length()>3)result=true;
		
		return result;
	}
	
	public String tryLogin(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		String result = SoptVars.FAIL;
		
		SoptHashMap hm = RequestManager.getRequest(request);
		if(hm.get("EMAIL")!=null && hm.get("PASSWORD")!=null){
			try {
				String encryptPw = CommUtil.getMD5(hm.get("PASSWORD").toString());
				hm.remove("PASSWORD");
				hm.put("PASSWORD", encryptPw);
				Object resultObj = sqlMapper.queryForObject("member.tryLogin", hm);
				if(resultObj!=null){
					hm = (SoptHashMap)resultObj;
					result = SoptVars.SUCCESS;
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(result.equals(SoptVars.SUCCESS)){
			request.getSession().setAttribute("SESSION_MEMBER_SEQ", hm.get("MEMBER_SEQ"));
			request.getSession().setAttribute("SESSION_MEMBER_NICK", hm.get("MEMBER_NICK"));
			request.getSession().setAttribute("SESSION_MEMBER_EMAIL", hm.get("MEMBER_EMAIL"));
		}
		
		return result;
	}
	
	public SoptHashMap getMemberInfoBySeq(String memSeq){
		SoptHashMap hm = null;
		try {
			hm = (SoptHashMap) sqlMapper.queryForObject("member.getMemberInfoBySeq",memSeq);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		return hm;
	}
	
	public SoptHashMap getMemberInfoByNick(String memNick){
		SoptHashMap hm = null;
		try {
			hm = (SoptHashMap) sqlMapper.queryForObject("member.getMemberInfoByNick",memNick);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		return hm;
	}
	
	public ArrayList getMembersGroup(String memSeq){
		ArrayList lt = null;
		try {
			lt =(ArrayList) sqlMapper.queryForList("member.getMembersGroup",memSeq);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lt;
	}
}
